import React from 'react';
import { DeviceEventEmitter, Image, ScrollView, StyleSheet, Text, TouchableOpacity, View, TextInput, ActivityIndicator } from 'react-native';

import { AlertDialog, SimpleItemsBottom } from 'react-native-pickers'
import CheckBox from 'react-native-check-box'

import Constant from '../Constant/Constant'
import ScreenUtils from '../Utils/ScreenUtils'
import ColorUtils from '../Utils/ColorUtils'
import ToastUtils from '../Utils/ToastUtils'
import HttpUtils from '../Utils/HttpUtils'
import RouterUtils from '../Utils/RouterUtils'
import StorageUtils from '../Utils/StorageUtils'

export default class PageAjzpSelect extends React.Component
{
    static navigationOptions = ({navigation}) => ({
        gesturesEnabled: false,//是否支持滑动返回收拾，iOS默认支持，安卓默认关闭
        headerTitle: navigation.state.params.title,
        headerStyle: {
            backgroundColor: ColorUtils.blue,
            height: ScreenUtils.statusBarHeight,
        },
        headerRight: (
            <TouchableOpacity onPress={() => DeviceEventEmitter.emit('addUser', 'param')}>
                <Text style={{color: ColorUtils.white, fontSize: ScreenUtils.Font_16, marginRight: 16}}>
                    保存
                </Text>
            </TouchableOpacity>
        ),
        headerTintColor: ColorUtils.white,
        headerTitleStyle: {
            fontSize: ScreenUtils.Font_18,
            color: ColorUtils.white,
            fontWeight: 'normal',
            flex: 1,
            alignSelf: 'center',
            textAlign: 'center',
        }
    });

    constructor(props)
    {
        super(props);
        this.state = {
            midTeamName: '请选择',
            midTeamCode: '',
            users: [],
            midTeams: [],
        };
    }

    componentDidMount()
    {
        RouterUtils.pushRouter('PageAjzpSelect', this.props.navigation.state.key);
        var that = this;
        this.listener1 = DeviceEventEmitter.addListener('addUser', function (event)
        {

            var indexArray = '';
            var nameArray = '';
            for (let i = 0; i < that.state.users.length; i++)
            {
                let item = that.state.users[i];
                if (item.isChecked)
                {
                    indexArray = indexArray + item.id + ',';
                    nameArray = nameArray + item.realName + ',';
                }
            }

            if (indexArray == '')
            {
                ToastUtils.toastShortCenter('请选择至少一名人员')
            } else
            {
                indexArray = indexArray.substr(indexArray, indexArray.lastIndexOf(','));
                nameArray = nameArray.substr(nameArray, nameArray.lastIndexOf(','));
                if (that.props.navigation.state.params.title == '选择执法人')
                {
                    if (indexArray.split(',').length > 1)
                    {
                        ToastUtils.toastShortCenter('执法人仅限一名')
                    } else
                    {
                        that.props.navigation.state.params.callback({'ids': indexArray, 'names': nameArray})
                        that.props.navigation.goBack();
                    }
                } else
                {
                    that.props.navigation.state.params.callback({'ids': indexArray, 'names': nameArray})
                    that.props.navigation.goBack();
                }
            }
        });
        this.getBigTeamList(); //汉阴
        // this.getMidTeamList(); //沣东
    }

    componentWillUnmount()
    {
        RouterUtils.popRouter('PageAjzpSelect', this.props.navigation.state.key);
        this.listener1.remove();
    }

    getBigTeamList()
    {
        try
        {
            var that = this;
            StorageUtils.get('session').then((session) =>
            {
                if (session != '' && session != null)
                {
                    HttpUtils.getJson(Constant.getBigTeamUserList, session, function (resultcode, data)
                    {
                        that.setState({
                            users: data,
                        });
                    }, function (resultcode, reason)
                    {
                        ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                    });
                }
            });
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    getMidTeamList()
    {
        try
        {
            var that = this;
            StorageUtils.get('session').then((session) =>
            {
                if (session != '' && session != null)
                {
                    HttpUtils.getJson(Constant.getMidTeamList, session, function (resultcode, data)
                    {
                        that.setState({
                            midTeams: data,
                        });
                    }, function (resultcode, reason)
                    {
                        ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                    });
                }
            });
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    getAjzpUserList()
    {
        try
        {
            var that = this;
            StorageUtils.get('session').then((session) =>
            {
                if (session != '' && session != null)
                {
                    HttpUtils.getJson(Constant.getAjzpUserMidList + '?deptId=' + that.state.midTeamCode, session, function (resultcode, data)
                    {
                        that.setState({
                            users: data,
                        });
                    }, function (resultcode, reason)
                    {
                        ToastUtils.toastShortBottom('错误码:' + resultcode + ',错误原因:' + reason);
                    });
                }
            });
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    switchCheck(item)
    {
        item.isChecked = !item.isChecked;
        this.setState({
            users: this.state.users
        })
    }

    renderUserList()
    {
        let allData = [];
        for (let i = 0; i < this.state.users.length; i++)
        {
            let item = this.state.users[i];
            allData.push(
                <TouchableOpacity key={item.id} onPress={() => this.switchCheck(item)}>
                    <View style={{height: 68, paddingLeft: 16, paddingRight: 16, paddingTop: 8, paddingBottom: 8, flexDirection: 'row', alignItems: 'center', borderBottomWidth: 1, borderBottomColor: '#EDEDED'}}>
                        <Image source={require("../img/user_head.png")} style={{width: 44, height: 44}}/>
                        <View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', marginLeft: 8}}>
                            <Text style={{fontSize: ScreenUtils.Font_16, color: ColorUtils.gray}}>{item.realName}</Text>
                        </View>
                        <CheckBox
                            onClick={() => this.switchCheck(item)}
                            isChecked={item.isChecked}
                            checkedImage={<Image resizeMode={Image.resizeMode.stretch} style={{width: 22, height: 22}} source={require('../img/check.png')}/>}
                            unCheckedImage={<Image resizeMode={Image.resizeMode.stretch} style={{width: 22, height: 22}} source={require('../img/uncheck.png')}/>}/>
                    </View>
                </TouchableOpacity>
            );
        }
        return allData;
    }

    //案件类型
    showCategoryItem()
    {
        if (this.state.gradeName == '请选择')
        {
            ToastUtils.toastShortCenter('请先选择案件级别')
            return;
        }
        this.midTeamsItemsDialog.show();
    }

    render()
    {
        return (
            <View style={styles.container}>
                {/*<View style={{justifyContent: 'center', alignItems: 'center', paddingLeft: 16, paddingRight: 16}}>*/}
                    {/*<TouchableOpacity activeOpacity={0.8} onPress={() => this.showCategoryItem()} style={{flexDirection: 'row', alignItems: 'center', height: 50, paddingTop: 8, paddingBottom: 8, borderBottomWidth: 1, borderBottomColor: ColorUtils.line}}>*/}
                        {/*<Text style={{flex: 1, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>选择中队</Text>*/}
                        {/*<Text style={{marginRight: 16, fontSize: ScreenUtils.Font_14, color: ColorUtils.black}}>{this.state.midTeamName}</Text>*/}
                        {/*<View style={{width: 14, justifyContent: 'center', alignItems: 'center'}}>*/}
                            {/*<Image style={{width: 9, height: 16}} source={require('../img/arrowright.png')}/>*/}
                        {/*</View>*/}
                    {/*</TouchableOpacity>*/}
                {/*</View>*/}
                <ScrollView keyboardShouldPersistTaps={'always'}>
                    <View style={{backgroundColor: 'white'}}>
                        {this.renderUserList()}
                    </View>
                </ScrollView>
                <SimpleItemsBottom
                    items={this.state.midTeams}
                    itemKey='deptName'
                    ref={ref => this.midTeamsItemsDialog = ref}
                    onPress={(pos) =>
                    {
                        this.setState({
                            midTeamName: this.state.midTeams[pos].deptName,
                            midTeamCode: this.state.midTeams[pos].id,
                        }, () =>
                        {
                            this.getAjzpUserList();
                        })
                    }}/>
            </View>

        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#ffffff',
    },
    demoOneBox: {
        padding: 10,
        flexDirection: 'row',
        alignItems: 'center',
    },

});


